import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;

/// 图片管理工具类
/// 负责将图片文件复制到应用本地目录并管理访问路径
class ImageManager {
  static const String _imageDirectoryName = 'plant_images';

  /// 获取应用文档目录
  static Future<Directory> get _appDocumentsDirectory async {
    final directory = await getApplicationDocumentsDirectory();
    return Directory(path.join(directory.path, _imageDirectoryName));
  }

  /// 确保图片目录存在
  static Future<void> _ensureImageDirectoryExists() async {
    final imageDir = await _appDocumentsDirectory;
    if (!await imageDir.exists()) {
      await imageDir.create(recursive: true);
    }
  }

  /// 复制图片文件到应用本地目录
  /// 返回新的文件路径
  static Future<String?> copyImageToLocal(File sourceFile) async {
    try {
      await _ensureImageDirectoryExists();

      final imageDir = await _appDocumentsDirectory;
      final fileName =
          '${DateTime.now().millisecondsSinceEpoch}_${path.basename(sourceFile.path)}';
      final destinationPath = path.join(imageDir.path, fileName);

      // 复制文件
      await sourceFile.copy(destinationPath);

      return destinationPath;
    } catch (e) {
      print('Error copying image: $e');
      return null;
    }
  }

  /// 从本地路径获取图片文件
  static File? getImageFile(String imagePath) {
    try {
      final file = File(imagePath);
      if (file.existsSync()) {
        return file;
      }
      return null;
    } catch (e) {
      print('Error getting image file: $e');
      return null;
    }
  }

  /// 删除本地图片文件
  static Future<bool> deleteImageFile(String imagePath) async {
    try {
      final file = File(imagePath);
      if (await file.exists()) {
        await file.delete();
        return true;
      }
      return false;
    } catch (e) {
      print('Error deleting image file: $e');
      return false;
    }
  }

  /// 检查图片文件是否存在
  static bool imageFileExists(String imagePath) {
    try {
      final file = File(imagePath);
      return file.existsSync();
    } catch (e) {
      print('Error checking image file: $e');
      return false;
    }
  }
}
